package com.example;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.entity.Student;
import com.example.R;

import java.util.ArrayList;
import java.util.List;

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentViewHolder> {
    private Context context;
    private List<Student> students;
    private LayoutInflater inflater;
    private OnStudentDeleteListener onStudentDeleteListener;

    public interface OnStudentDeleteListener {
        void onStudentDeleted(Student student);
    }

    public StudentAdapter(Context context, List<Student> students, OnStudentDeleteListener listener) {
        this.context = context;
        this.students = students;
        this.inflater = LayoutInflater.from(context);
        this.onStudentDeleteListener = listener;
    }

    public class StudentViewHolder extends RecyclerView.ViewHolder {
        TextView nameTextView;
        TextView idTextView;

        public StudentViewHolder(@NonNull View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.p_name);
            idTextView = itemView.findViewById(R.id.p_id);
            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (onStudentDeleteListener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            Student studentToDelete = students.get(position);
                            onStudentDeleteListener.onStudentDeleted(studentToDelete);
                        }
                    }
                    return true;
                }
            });
        }
    }

    @NonNull
    @Override
    public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.student_item, parent, false);
        return new StudentViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull StudentViewHolder holder, int position) {
        Student student = students.get(position);
        holder.nameTextView.setText(student.getStudentName());
        holder.idTextView.setText(student.getStudentId());
    }

    @Override
    public int getItemCount() {
        return students.size();
    }

    // 更新学生列表并通知数据集改变
    @SuppressLint("NotifyDataSetChanged")
    public void updateStudentList(List<Student> newStudents) {
        students = newStudents;
        notifyDataSetChanged();
    }
}